<?php
/**
 * AutoGenerate.php
 * Create by PhpStorm
 * @author: sx
 * @date: 2021/9/28 15:45
 */

namespace app\admin\controller;


use app\common\model\goods\Goods;
use app\common\service\goods\GoodsBrandService;
use app\common\service\goods\GoodsCategoryService;
use app\common\service\goods\GoodsService;
use app\common\service\order\OrderListConfigService;
use app\common\service\order\OrderListCustomerService;
use app\common\service\PhpExcelService;
use app\common\service\supplier\SupplierService;
use app\common\tools\XLSXWriter;
use think\Db;

class AutoGenerate extends Base{

    const shopUid = 0;
    function customer(){
//        pj(123);
        if (request()->isAjax()) {
            $data = input();
            $op['page'] = isset($data['page']) ? intval($data['page']) : 1;
            $op['doPage'] = true;
            $op['field'] = '*';
            $op['limit'] = $data['limit'] ?? 10;
            $op['order'] = 'id desc';
            $op['shop_uid'] = self::shopUid;
            $list = OrderListCustomerService::getModel()->getList($op);
            $res = ['count' => $list['count'], 'data' => $list['list']];
            return adminOut($res);
        }
//        pj(2);
//        echo 333;
        $this->assign('funName', 'customer');
        return $this->fetch();
    }

    function downExcelDemo(){
        return download('./download/order_list_customer.xlsx', '导入模板');
    }

    function excelCustomerList(){
        $file = request()->file('file');
        $res = OrderListCustomerService::excelList($file);
        return adminOut($res);
    }

    function config(){
        $shopUid = 0;
        $catWhere[] = ['parent_id', '=', 0];
        $catWhere[] = ['shop_uid', '=', $shopUid];
//        $catWhere[] = ['is_show', '=', 1];
        $order = 'sort_order';
        $field = 'cat_id, cat_name';
        $catList = GoodsCategoryService::getModel($shopUid)->field($field)->where($catWhere)->order($order)->select();

        $op['doPage'] = false;
        $list = OrderListConfigService::getModel()->getList($op);
        $baseConfig = $list['list'][0];
        $baseConfig['order_time'] = date("Y-m", $baseConfig['cat_id']);
        $itemFirst = json_decode($baseConfig['buy_num_rate'], 1);
        $baseConfig['order_count'] = $itemFirst['order_count'];
        $baseConfig['order_amount'] = $itemFirst['order_amount'];
        $baseConfig['customer_count'] = $itemFirst['customer_count'] ?? 0;

        if (request()->isAjax()) {
//pj($list);
            unset($list['list'][0]);
            $list['list'] = array_values($list['list']);
            $list['count'] = count($list['list']);
            foreach ($list['list'] as &$item) {
                $item['buy_num_rate'] = json_decode($item['buy_num_rate'], 1);
            }

            $res = ['count' => $list['count'], 'data' => $list['list'], 'baseConfig' => $baseConfig];
            return adminOut($res);
        }


//pj($catList);
        $this->assign('baseConfig', $baseConfig);
        $this->assign('catList', $catList);
        $this->assign('funName', 'config');
        return $this->fetch();
    }

    function delConfig(){
        $data = input();

        $res = OrderListConfigService::getModel()->del($data['id']);
        return $res ? successReturn('删除成功') : errorReturn('删除失败');
    }

    //保存基础配置
    function saveOrderConfig(){
        $data = input();
        $data['id'] = 1;
        $data['cat_id'] = is_numeric($data['order_time']) ? $data['order_time'] : strtotime($data['order_time']);

        $data['buy_num_rate'] = [
            'order_count' => $data['order_count'] ?? 0,
            'order_amount' => $data['order_amount'] ?? 0,
            'customer_count' => $data['customer_count'] ?? 0,   //下单会员数量
//            'total_supplier' => $data['total_supplier'] ?? 0,   //合作供应商
        ];
//        $data['buy_num'] = $data['order_count'];
//        $data['rate'] = $data['order_amount'];

        $upRes = OrderListConfigService::getModel()->updateById($data['id'], $data);
        if(!$upRes){
            return  errorReturn('保存失败');
        }

        return adminOut(['data' => $data, 'msg' =>'保存成功']);
    }

    function saveConfig(){
        $data = input();
        $info = [];
        $data['buy_num_rate'] = is_string($data['buy_num_rate']) ? json_decode(htmlspecialchars_decode($data['buy_num_rate']), 1) : $data['buy_num_rate'];
        if(isset($data['id']) && $data['id'] > 0){  //修改
            unset($data['create_time']);
            unset($data['update_time']);
            $buy_num_rate = [];
            foreach ($data['buy_num_rate'] as $key => $val){
                $temp = [];
                foreach ($val as $k => $v){
                    if($k != 'LAY_TABLE_INDEX'){
                        $temp[$k] = $v;
                    }
                }
                $buy_num_rate[] = $temp;
            }
            $data['buy_num_rate'] = $buy_num_rate;
            $upRes = OrderListConfigService::getModel()->updateById($data['id'], $data);
            if(!$upRes){
                return  errorReturn('保存失败');
            }
        }else{
            $insertData['cat_id'] = $data['cat_id'];
            $insertData['cat_name'] = $data['cat_name'];
            $insertData['rate'] = $data['rate'];
            $insertData['buy_num'] = $data['buy_num'];
            $insertData['buy_num_rate'] = $data['buy_num_rate'];
            $insertData['create_time'] = time();

            foreach ($data['buy_num_rate'] as $key => $val){
                $temp = [];
                foreach ($val as $k => $v){
                    if($k != 'LAY_TABLE_INDEX'){
                        $temp[$k] = $v;
                    }
                }
                $buy_num_rate[] = $temp;
            }
            $insertRes = OrderListConfigService::getModel()->insertGetId($insertData);
            if($insertRes){
                $data = OrderListConfigService::getModel()->info($insertRes);
            }
        }
        return adminOut(['data' => $data, 'msg' =>'保存成功']);
    }



    const buyNumRate = 'buy_num_rate';
    const catList = [
        "3787"=> ['cat_id' => 3787, 'rate' => 0, 'buy_num_rate' =>[]],
        "3788"=> ['cat_id' => 3788, 'rate' => 0, 'buy_num_rate' =>[]],
        "3885"=> ['cat_id' => 3885, 'rate' => 0, 'buy_num_rate' =>[]],
        "3951"=> ['cat_id' => 3951, 'rate' => 0, 'buy_num_rate' =>[]],
        "4015"=> ['cat_id' => 4015, 'rate' => 0, 'buy_num_rate' =>[]],
        "4027"=> ['cat_id' => 4027, 'rate' => 0, 'buy_num_rate' =>[]],
        "4028"=> ['cat_id' => 4028, 'rate' => 0, 'buy_num_rate' =>[]],
//软装灯具
        "5485"=> ['cat_id' => 5485,'rate' => 50, 'buy_num_rate' =>[
            ['buyNum' => 1, 'buyRate' => 99.10,],
            ['buyNum' => 2, 'buyRate' => 0.24,],
            ['buyNum' => 3, 'buyRate' => 0.23,],
            ['buyNum' => 4, 'buyRate' => 0.22,],
            ['buyNum' => 5, 'buyRate' => 0.21,],
        ]],
//qc商品分类
        "13212"=> ['cat_id' => 13212,'rate' => 40, 'buy_num_rate' =>[
            ['buyNum' => 1, 'buyRate' => 81,],
            ['buyNum' => 2, 'buyRate' => 9,],
            ['buyNum' => 3, 'buyRate' => 5,],
            ['buyNum' => 4, 'buyRate' => 3,],
            ['buyNum' => 5, 'buyRate' => 2,],
        ]],
//套餐包2
        "13221"=> ['cat_id' => 13221,'rate' => 10, 'buy_num_rate' =>[
            ['buyNum' => 1, 'buyRate' => 82,],
            ['buyNum' => 2, 'buyRate' => 8,],
            ['buyNum' => 3, 'buyRate' => 5,],
            ['buyNum' => 4, 'buyRate' => 3,],
            ['buyNum' => 5, 'buyRate' => 2,],
        ]],
    ];

//    const totalOrderCount = 100;
//    const totalOrderAmount = 10000.00;




    function getConfig(){
        $op['where'][] = ['delete_time', '=', 0];
        $op['field'] = '*';
        $catList = OrderListConfigService::getModel()->getList($op)['list'];
        $catList = array_column($catList, null, 'cat_id');
        $totalOrderCount = $totalOrderAmount = $orderTime = 0;
        foreach ($catList as $key => &$item) {
            $item['buy_num_rate'] = json_decode($item['buy_num_rate'], 1);

            if($item['id'] == 1){   //id=1的是总配置,  懒的另外建一张表了
                $baseConfig = $item['buy_num_rate'];

                $orderTime          = $item['cat_id'];  //下单日期
                $totalOrderCount    = intval($baseConfig['order_count']);  //购买订单的总数量
                $totalOrderAmount   = $baseConfig['order_amount'];//购买订单的总金额
                $totalCustomerCount = $baseConfig['customer_count'];//总下单会员
                unset($catList[$key]);
            }

        }
        return [
            'catList' => $catList,
            'totalOrderCount' => $totalOrderCount,
            'totalOrderAmount' => $totalOrderAmount,
            'orderTime' => $orderTime,
            'totalCustomerCount' => $totalCustomerCount,
        ];
    }

    function order(){
        $shopUid = 0;
        $config = $this->getConfig();
//pj($config);
        $catBase = $config['catList'];
        $totalOrderCount = $config['totalOrderCount'];
        $totalOrderAmount = $config['totalOrderAmount'];

        $catRateList = [];  //每个分类对应的比例 , 例如    {"5485": 5000,"13212": 4000,"13221": 1000}
        $catRateListAll = array_column($catBase, 'rate', 'cat_id');
        foreach ($catRateListAll as $key => $catRate) {
            if ($catRate <= 0) continue;
            $catRateList[$key] = bcmul($catRate, 100);
        }

        $catOrderNum = [];  //各个分类对应的订单数量, 例如   {"5485": 515, "13212": 388, "13221": 97}
        for($i=0; $i< $totalOrderCount; $i++){
            $res = $this->getRand($catRateList);
            !isset($catOrderNum[$res]) && $catOrderNum[$res] = 0;
            $catOrderNum[$res] = $catOrderNum[$res] + 1;
        }
        ksort($catOrderNum);
//pj($catOrderNum, 0);
        $catBuyNumArray = [];   //每个分类每一单的购买数量 例如{"5485": [1,1,1,....],13212": [1,3,2,....]}
        $catGoodsArray = [];    //每个分类下的 key=商品,val=goods_id对应的价格, 例如{"5485": {"33254": "139.00", "33259": "99.00", "33524": "2.00",....},13212": {"38500": "500.00", "38501": "45.00",....},}
        foreach ($catOrderNum as $key => $item) {
            //取配置信息
            $buyNumRate = $catBase[$key][self::buyNumRate];
            //把配置信息变成 数量为key, 比例为值的数组, 例如 {"1": "9910","2": "24","3": "23","4": "22","5": "21"}
            $buyRate = [];
            foreach ($buyNumRate as $k => $val) {
                $buyRate[$val['buyNum']] = bcmul($val['buyRate'], 100);
            }
            $arr = [];
            for($i=0; $i< $item; $i++){
                $arr[] = $this->getRand($buyRate);
            }
            $catBuyNumArray[$key] = $arr;


            //取当前分类下级所有分类 的商品
            $resGetCatGoods = $this->getCatGoods($shopUid, $key, 0);
            if($resGetCatGoods['result']){
                $catGoodsArray[$key] = $resGetCatGoods['data'];
            }
        }

//pj($catBuyNumArray, 1 );
//pj($catGoodsArray, 1);

        $exportOrderList = $this->autoGenerateOrder($shopUid, $catBuyNumArray, $catGoodsArray, $catOrderNum, $config);
//pj($exportOrderList);


        $orderTime = $config['orderTime'] ?? 0;
        $title = date('Y年m月订单', $orderTime);
        /*
        $exportConfig = [
            ['width'=>10,'title'=>'序号','column'=>'number'],
            ['width'=>10,'title'=>'订单类型','column'=>'source_type'],
            ['width'=>20,'title'=>'订单号','column'=>'order_sn'],
            ['width'=>20,'title'=>'客户单号','column'=>'kh_order_sn'],
            ['width'=>5,'title'=>'销售单号','column'=>'sale_order_sn'],
            ['width'=>15,'title'=>'客户/供应商','column'=>'source'],
            ['width'=>15,'title'=>'订单日期','column'=>'order_time'],
            ['width'=>20,'title'=>'发货单位','column'=>'fahuo_unit'],
            ['width'=>15,'title'=>'发货人','column'=>'fahuo_user_name'],
            ['width'=>20,'title'=>'发货地址','column'=>'fahuo_address'],
            ['width'=>20,'title'=>'收货单位','column'=>'unit'],
            ['width'=>5,'title'=>'收货人','column'=>'user_name'],
            ['width'=>15,'title'=>'收货人电话','column'=>'tel'],
            ['width'=>20,'title'=>'收货地址','column'=>'address'],
            ['width'=>10,'title'=>'归属省份','column'=>'province'],
            ['width'=>10,'title'=>'归属市区','column'=>'city'],
            ['width'=>10,'title'=>'归属县区','column'=>'district'],
            ['width'=>15,'title'=>'要求到达日期','column'=>'ship_end_time'],

            ['width'=>20,'title'=>'商品编码','column'=>'goods_code'],
            ['width'=>20,'title'=>'商品名称','column'=>'goods_name'],
            ['width'=>20,'title'=>'商品规格','column'=>'goods_guige'],
            ['width'=>20,'title'=>'商品型号','column'=>'goods_model'],
            ['width'=>10,'title'=>'商品颜色','column'=>'goods_color'],
            ['width'=>10,'title'=>'商品品类','column'=>'goods_type'],
            ['width'=>10,'title'=>'商品品牌','column'=>'goods_brand'],
            ['width'=>5,'title'=>'数量','column'=>'total_num'],
            ['width'=>10,'title'=>'数量单位','column'=>'num_unit'],
            ['width'=>5,'title'=>'面积','column'=>'area'],
            ['width'=>10,'title'=>'计价单位','column'=>'jijia_unit'],
            ['width'=>10,'title'=>'商品单价','column'=>'price'],
            ['width'=>5,'title'=>'价格系数','column'=>'xishu'],
            ['width'=>10,'title'=>'总金额','column'=>'total_price'],
            ['width'=>10,'title'=>'采购价','column'=>'purchase_price'],
            ['width'=>5,'title'=>'采购总金额','column'=>'total_purchase_price'],
            ['width'=>5,'title'=>'备注','column'=>'remark'],

        ];
        $res = PhpExcelService::exportZhongDian($exportOrderList, $exportConfig, $title);
        PhpExcelService::excelOut($title,$res);
        */

        $filename = "{$title}.xlsx";
        $header = array(
            'number'        =>'string',
            'source_type'   =>'string',
            'order_sn'   =>'string',
            'kh_order_sn'   =>'string',
            'sale_order_sn'   =>'string',
            'source'   =>'string',
            'order_time'   =>'string',
            'fahuo_unit'   =>'string',
            'fahuo_user_name'   =>'string',
            'fahuo_address'   =>'string',
            'unit'   =>'string',
            'user_name'   =>'string',
            'tel'   =>'string',
            'address'   =>'string',
            'province'   =>'string',
            'city'   =>'string',
            'district'   =>'string',
            'ship_end_time'   =>'string',

            'goods_code'   =>'string',
            'goods_name'   =>'string',
            'goods_guige'   =>'string',
            'goods_model'   =>'string',
            'goods_color'   =>'string',
            'goods_type'   =>'string',
            'goods_brand'   =>'string',
            'total_num'   =>'string',
            'num_unit'   =>'string',
            'area'   =>'string',
            'jijia_unit'   =>'string',
            'price'   =>'price',
            'xishu'   =>'string',
            'total_price'   =>'price',
            'purchase_price'   =>'price',
            'total_purchase_price'   =>'price',
            'remark'   =>'string',
        );

//$header = array(
//    'created'=>'date',
//    'product_id'=>'integer',
//    'quantity'=>'#,##0',
//    'amount'=>'price',
//    'description'=>'string',
//    'tax'=>'[$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00',
//);
//$exportOrderList = array(
//    array('2015-01-01',873,1,'44.00','misc','=D2*0.05'),
//    array('2015-01-12',324,2,'88.00','none','=D3*0.05'),
//);
        PhpExcelService::xlsxWriterExport($filename, $header, $exportOrderList);

        exit();

    }

    /**
     * Notes: 生成各个分类对应的每笔订单
     * @param array $shopUid
     * @param array $catBuyNumArray     每个分类每一单的购买数量, 例如{"5485": [1,1,1,....],"13212": [1,3,2,....]}
     * @param array $catGoodsArray      每个分类下的 key=商品,val=id对应的价格, 例如{"5485": {"33254": "139.00", "33259": "99.00", "33524": "2.00",....},13212": {"38500": "500.00", "38501": "45.00",..},}
     * @param array $catOrderNum        各个分类对应的订单数量, 例如   {"5485": 515, "13212": 388, "13221": 97}
     * @param array $config  totalOrderAmount:总订单金额, totalOrderCount:总订单数,  orderTime:下单时间
     * @return array
     * User: SongX DateTime: 2021/10/7 16:33
     */
    function autoGenerateOrder($shopUid, $catBuyNumArray = [], $catGoodsArray = [], $catOrderNum = [], $config){
        if(empty($catBuyNumArray) || empty($catGoodsArray) || empty($catOrderNum)){
            return errorReturn('参数不能为空');
        }

        $totalOrderAmount = $config['totalOrderAmount'] ?? 0;
        $totalOrderCount = $config['totalOrderCount'] ?? 0;
        $orderTime2 = $orderTime = $config['orderTime'] ?? 0;
        $monthDays = date('t', $orderTime);
        $monthAvgDays = intval($totalOrderCount / $monthDays );

        $avgCounter = 1;
        $dayCounter = 1;
        $everyDayArr = $everyDayStrArr = [];
        for($i=0; $i< $totalOrderCount; $i++){
            $everyDayArr[] = $orderTime2;
            if($avgCounter == $monthAvgDays && $dayCounter < $monthDays){
                $avgCounter = 1;
                $orderTime2 = $orderTime2 + 86400;
                $dayCounter++;
            }else{
                $avgCounter++;
            }
        }



        //洗牌算法
        $everyDayArr = wash_card($everyDayArr);
//pj($everyDayArr);
//$acv=array_count_values($everyDayStrArr);
//arsort($acv);
//pj(array_values($acv));
//pj($monthAvgDays);
        $totalCustomerCount = $config['totalCustomerCount'] ?? 0;
//pj($catGoodsArray, 0);
//pj($catOrderAmount,0);
//pj($catBuyNumArray, 0);
        $catOrderAmount = [];
        $orderRandArr = [];
        $sum = 0;
//pj($catOrderNum, 0);
//pj($catGoodsArray);

        foreach ($catOrderNum as $key => $item) {
            $rate = bcdiv($item, $totalOrderCount, 4);
            $catOrderAmount[$key] = bcmul ($totalOrderAmount, $rate, 2);
            //生成各个分类对应的每笔订单金额
            $rrr = $this->orderCalculation($catGoodsArray[$key], $catOrderAmount[$key], $catBuyNumArray[$key]);
            $ratio = $rrr['sumAmount'] / $catOrderAmount[$key];
            $abs = abs($ratio - 1);
            $loopIndex = 1; //第几次模拟
            $loopMax = 10;  //最多再模拟次数,  10
            if( $abs > 0.01 ){  //误差1% 以上就重新模拟
                while ($loopIndex <= $loopMax){
                    $tempR = $this->orderCalculation($catGoodsArray[$key], $catOrderAmount[$key], $catBuyNumArray[$key]);
                    $ratioR = $tempR['sumAmount'] / $catOrderAmount[$key];
                    $tempAbs = abs($ratioR - 1);
                    if($tempAbs < $abs){
                        $rrr = $tempR;
                        $abs = $tempAbs;
                    }
                    $loopIndex++;
                }

            }
            $orderGoodIdArr[$key] = $rrr['data'];
            $orderSumAmount[$key] = $rrr['sumAmount'];

            $orderRandArr[$key]['cid']          = $key;
            $orderRandArr[$key]['gid']          = $rrr['data'];
            $orderRandArr[$key]['sumAmount']    = $rrr['sumAmount'];
            $orderRandArr[$key]['buyNumDetail'] = $catBuyNumArray[$key];
            $orderRandArr[$key]['orderNum']    = $item;

            $sum = bcadd($rrr['sumAmount'], $sum, 2);;
        }
//        $orderRandArr['sum'] = (float)$sum;
//pj($catBuyNumArray, 0);
//pj("sum---->>>{$sum}", 0);
//pj(array_column($orderRandArr, 'sumAmount', 'cid'), 1);

//pj($catOrderNum, 0);

        $exportOrderList = [];
        $xuHao = 1;


        $catIdArr = array_keys($orderRandArr);
        $optionsCat['where'][] = ['shop_uid', '=', $shopUid];
        $optionsCat['where'][] = ['cat_id', 'in', $catIdArr];
        $optionsCat['where'][] = ['level', '=', 1];
        $catList = GoodsCategoryService::getModel($shopUid)->getList($shopUid, $optionsCat)['list'];
        $catList = array_column($catList, 'cat_name', 'cat_id');
//pj($orderRandArr);

        //$customerList --> 上传的下单商家中随机抽取, 要符合下单总会员数量
//        $customerAllList = [];
//        foreach ($orderRandArr as $catId => $itemCat) {
//            $sql = "SELECT t1.* FROM `zsp_order_list_customer` AS t1 JOIN
//            (SELECT ROUND( RAND () * (SELECT MAX(id) FROM `zsp_order_list_customer`)) AS id) AS t2
//WHERE t1.id >= t2.id
//ORDER BY t1.id ASC LIMIT {$itemCat['orderNum']};";
//            $customerList = Db::query($sql);
//            $customerAllList[$catId] = $customerList;
//        }

        $customerAllList = $this->customerRandCount($orderRandArr, $totalCustomerCount);
//foreach ($customerAllList as $catId => $item22) {
//    $co = count($item22);
//    echo "catId -> {$catId}####count-> {$co}<br>";
//}
//exit(11);
//pj($customerAllList);
        foreach ($orderRandArr as $catId => $itemCat) {
//pj($orderRandArr);
            //$supplier --> 供应商信息
            $resSupplier = $this->getSupplierByGidArr($shopUid, $itemCat['gid']);
//pj($resSupplier);
            $supplier = $resSupplier['data'];


//pj($itemCat['orderNum'],0);
//pj($supplier);
            $customerList = $customerAllList[$catId];
            for($i=0; $i< $itemCat['orderNum']; $i++){

                $gid = $itemCat['gid'][$i];
                $buyNum = $itemCat['buyNumDetail'][$i];
if(!isset($customerList[$i])){
    echo $i."---".$itemCat['orderNum'];
    pj(count($customerList));
    exit();
}
                $customer = $customerList[$i];
                $orderTime = $everyDayArr[$xuHao-1];
                $temp = [];
                $temp[0] = $xuHao;
                $temp[1] = '厂家直供';
                $temp[2] = 'CJZG'. date('YmdHis', time() + $i);
                $temp[3] =  'LS'. date('YmdHis', time() + $i);
                $temp[4] = '';
                $temp[5] = '战略会员';
                $temp[6] = date('Y-m-d', $orderTime);               //G
//                $temp[6] = $orderTime;               //G
                //供应商信息 即发货单位, 发货联系人, 地址
                $temp[7] = $supplier[$gid]['supplier']['supplier_name'];    //H
                $temp[8] = $supplier[$gid]['supplier']['contact'];
                $temp[9] = $supplier[$gid]['supplier']['address'];
                //收货信息
                $temp[10] = $customer['customer_name']; //K
                $temp[11] = $customer['contact'];
                $temp[12] = $customer['contact_phone'];
                $temp[13] = $customer['contact_address'];
                $temp[14] = $customer['province'];
                $temp[15] = $customer['city'];
                $temp[16] = $customer['district'];  //Q
                $temp[17] = date('Y-m-d', $orderTime + 86400 * 7);  //R



                //商品信息
                /*
                ['width'=>50,'title'=>'商品编码','column'=>'goods_code'],
                ['width'=>50,'title'=>'商品名称','column'=>'goods_name'],
                ['width'=>50,'title'=>'商品规格','column'=>'goods_guige'],
                ['width'=>50,'title'=>'商品型号','column'=>'goods_model'],
                ['width'=>50,'title'=>'商品颜色','column'=>'goods_color'],
                ['width'=>50,'title'=>'商品品类','column'=>'goods_type'],
                ['width'=>50,'title'=>'商品品牌','column'=>'goods_brand'],
                 */
                $goodsData = getSpecsModelBrand($supplier[$gid]['goods_name']);
                $temp[18]  = $supplier[$gid]['goods_sn'];     //S
                $temp[19]  = $supplier[$gid]['goods_name'];
                $temp[20] = $goodsData['specs']; //商品规格
                $temp[21] = $goodsData['model']; //商品型号
                $temp[22] = ''; //商品颜色
                $temp[23]  = $catList[$catId] ?? ''; //商品品类
                $temp[24] = $supplier[$gid]['brand_name']; //商品品牌  Y

                //↓↓↓↓↓ 价格计算相关信息 ↓↓↓↓↓
                /*
                ['width'=>50,'title'=>'数量','column'=>'total_num'],
                ['width'=>50,'title'=>'数量单位','column'=>'num_unit'],
                ['width'=>50,'title'=>'面积','column'=>'area'],
                ['width'=>50,'title'=>'计价单位','column'=>'jijia_unit'],
                ['width'=>50,'title'=>'商品单价','column'=>'price'], AD 29
                ['width'=>50,'title'=>'价格系数','column'=>'xishu'], AE 30
                ['width'=>50,'title'=>'总金额','column'=>'total_price'], AF 31
                ['width'=>50,'title'=>'采购价','column'=>'purchase_price'], AG 32
                ['width'=>50,'title'=>'采购总金额','column'=>'total_purchase_price'],  AH 33
                ['width'=>50,'title'=>'备注','column'=>'remark'], AI 34
                 */


                $temp[25]      = $buyNum;  //Z 数量
                $temp[26]       = $supplier[$gid]['goods_unit'];   //AA 数量单位 num_unit
                //面积
                if(!isset($supplier[$gid]['sale_set']) || $supplier[$gid]['sale_set'] == 0){
                    $temp[27]       = 0;  //AB 没有配置件数比,  面积=0
                    $temp[28] =  '数量';   //计价单位 AC
                }else{
                    $stockArea = $supplier[$gid]['goods_extend']['stock_area'] ?? 0;
                    $stockArea && $temp[27] = bcCalc($stockArea, '*', $buyNum, 4);
                    $temp[28] = '面积';   //计价单位 AC
                }

                //单价
                $purchase_price  = $purchasePrice = $supplier[$gid]['purchase_price'] ?? 0;
                if($purchase_price <=0){    //取采购价出错, 尝试从version_cost_price解析出来
                    $version_cost_price = $supplier[$gid]['version_cost_price'] ?? '';
                    $version_cost_price_arr = json_decode($version_cost_price, 1);
                    $purchase_price = $version_cost_price_arr['v2'] ?? 0;
                }
                $temp[29]   = $purchase_price;
                $temp[30]   = 1;
                $temp[31]   = bcCalc($purchasePrice, '*', $buyNum, 2);  //直接 采购价* 数量,  暂时不考虑件数比
                $temp[32]   = $supplier[$gid]['cost_price'] ?? 0;
                $temp[33]   = bcCalc($temp[32], '*', $buyNum, 2);;
                $temp[34]   = '';
                //↑↑↑↑↑ 价格计算相关信息 ↑↑↑↑↑


                $exportOrderList[] = $temp;
                $xuHao++;

            }

        }
        $number = array_column($exportOrderList, 6);
        array_multisort($number, SORT_ASC, $exportOrderList);

        return $exportOrderList;

//        foreach ( as $item) {
//
//        }


    }

    /**
     * Notes: 上传的下单商家中随机抽取, 要符合下单总会员数量
     * @param $orderRandArr array
     * @param $totalCustomerCount int 总下单会员数量
     * @return array
     * User: SongX DateTime: 2022/2/10 14:34
     */
    function customerRandCount($orderRandArr, $totalCustomerCount){

        $customerAllList = $return = [];
        foreach ($orderRandArr as $catId => $itemCat) {
            $sql = "SELECT t1.* FROM `zsp_order_list_customer` AS t1 JOIN 
            (SELECT ROUND( RAND () * ((SELECT MAX(id) FROM `zsp_order_list_customer`) - {$itemCat['orderNum']}) ) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id ASC LIMIT {$itemCat['orderNum']};";
            //$customerList --> 上传的商家中随机抽取
            $customerList = Db::query($sql);
            //$customerAllList,  所有的下单商家会员
            $customerAllList = array_merge($customerAllList, $customerList);
            $return[$catId] = $customerList;
//$catCount = count($customerList);
//echo "<br> customerAllListCount -> {$catCount} <br>";
        }
//pj($customerAllList);
        $allCount = count($customerAllList);
//echo "<br><br> customerAllListCount -> {$allCount} <br><br>";
        //总数量和 配置的下单会员数量的差,  即需要替换成重复的商家会员
        $randCount = $allCount - $totalCustomerCount;
//pj($totalCustomerCount.'--'.$allCount, 0);
        if($allCount <= $totalCustomerCount){
            return $return;
        }
//pj($randCount);
        //从第一个开始复制
        $copyIndex = 0;
        $maxLoopNum = $totalCustomerCount;
        for($i=1; $i<= $randCount; ){

            $customerRepeatNum = mt_rand(1, 3); //重复下单的数量;, 至少重复1次, 最大为2数之差
            if($maxLoopNum == 1){
                $customerRepeatNum = $randCount;
            }
//echo "<br><br>↓↓↓↓↓↓↓↓↓↓↓↓↓↓customerRepeatNum->{$customerRepeatNum}---{$copyIndex}↓↓↓↓↓↓↓↓↓↓↓↓↓↓<br>";
            for($j=0; $j< $customerRepeatNum; $j++){


                $replace = $allCount - $i;
                $customerAllList[$replace] = $customerAllList[$copyIndex];
//echo " i->{$i}#rand->{$replace}<br>";
                if($i == $allCount){
                    break;
                }
                $i++;
                if($i > $randCount){
                    break;
                }
            }
            if($copyIndex >= $randCount){
                break;
            }
            $copyIndex++;
            $maxLoopNum--;

        }

        //洗牌算法
        for($i= $allCount - 1; $i>0; $i--){
            //随机数生成器，范围[0, i]
            $rand = mt_rand(0, $i);

            $temp = $customerAllList[$i];
            $customerAllList[$i] = $customerAllList[$rand];
            $customerAllList[$rand] = $temp;

        }

        $tempList = $customerAllList;

        $idArr = array_column($customerAllList, 'id');
//pj($idArr, 0);
        $index = 0;
        foreach ($orderRandArr as $catId => $itemCat) {
            $indexEnd = $index + $itemCat['orderNum'];

            $return[$catId] = array_slice($tempList, $index, $itemCat['orderNum']);

//echo "{$itemCat['orderNum']}<br>";
//$return[$catId] = array_slice($idArr, $index, $itemCat['orderNum']);

            $index = $indexEnd;
        }
//pj($return);
//$idArr = array_column($customerAllList, 'id');
//$idArr = array_unique($idArr);
//pj(count($idArr).'---'.$randCount, 0);
//pj(array_values($idArr));

//$acv=array_count_values($idArr);
//arsort($acv);
//pj(array_values($acv));
        return $return;
    }

    /**
     * Notes:
     * @param array $goodsArray     商品单价数组 例如{"33526":"0.05","33524":"2.00","38521":"90.00","33259":"99.00","34293":"110.00","33254":"139.00","38522":"450.00","34272":"1299.00","34270":"3999.00"}
     * @param float $totalOrderAmount   总订单金额
     * @param array $buyNumArray    购买数量数组 例如[1,1,2,1,3,1,1,1,1,1,4,1,1,1,1,1,1, ....]
     * User: SongX DateTime: 2021/10/8 17:14
     */
    function orderCalculation($goodsArray, $totalOrderAmount, $buyNumArray){
        //{"order_count": "7297", "order_amount": "44958325.6", "customer_count": "4142"}
        asort($goodsArray);

        $tempOrderNumArray = count($buyNumArray);
$test = [];
        $sumRandAmount = 0;
        $goodsKeyArr = [];
        foreach ($buyNumArray as $buyNum){
            $tempGoodsArray = [];
            if($totalOrderAmount <= 0){
                $tempGoodsArray = $goodsArray;
            }
            $avg = $totalOrderAmount / $tempOrderNumArray / $buyNum;    //平均单价

            $minPrice = $avg * 0.8;
            $maxPrice = $avg * 1.2;
            //商品单价筛选
            $first = true;
            foreach ($goodsArray as $k => $price){

                if($price < $minPrice){
                    continue;
                }
                if($price > $maxPrice){
                    continue;
                }
                if($first){
                    $tempGoodsArray[$k] = $price;
                    $first = false;
                    continue;
                }
                $tempGoodsArray[$k] = $price;
            }
//pj($tempGoodsArray, 0);
            if(empty($tempGoodsArray)){
                $tempGoodsArray = $goodsArray;
//                echo "empty tempGoodsArray avg-->{$avg}";
//pj($goodsArray);
            }
//pj($minPrice.'----'.$maxPrice, 0);
            //随机从符合的商品单价中选中一个
            $randKey = array_rand($tempGoodsArray);
            $randPrice = $tempGoodsArray[$randKey];
            $thisOrderTotalAmount = $randPrice * $buyNum;
$test[] = [$randKey,$thisOrderTotalAmount];
            $goodsKeyArr[] = $randKey;
            $sumRandAmount = bcadd($thisOrderTotalAmount, $sumRandAmount, 2);
            $totalOrderAmount -= $thisOrderTotalAmount;
            $tempOrderNumArray--;
        }
//        $min
//pj($tempGoodsArray, 0);
//pj($randKey, 0);
//pj(count($buyNumArray), 0);
//pj(count($goodsKeyArr), 0);
//pj($totalOrderAmount, 0);
//pj($buyNumArray, 0);
//pj($sumRandAmount, 0);
//pj($goodsKeyArr, 0);
//pj($test);

        return successReturn(['data' =>$goodsKeyArr, 'sumAmount' => $sumRandAmount]);
    }

    //根据分类获取 所有商品的 purchase_price 采购价(目前是最低的采购价)
    private function getCatGoods($shopUid, $catId, $cacheTime= 3600){
        $cacheKey = 'AutoGenerate_getCatGoods_'.$catId;
        $rs = cache($cacheKey);
        if($cacheTime > 0 && $rs !== false){
            return successReturn(['data' => json_decode($rs, true)]);
        }

        $catInfo = GoodsCategoryService::getModel($shopUid)->info($catId, $shopUid);
        if(empty($catInfo)){
            return errorReturn('商品分类错误');
        }
        $options['where'][] = ['shop_uid', '=', $shopUid];
        $options['where'][] = ['top_cat_id', '=', $catId];
        $options['where'][] = ['level', '>=', $catInfo['level']];
        $options['where'][] = ['is_show', '=', 1];
        $options['order'][] = 'level desc';
        $catList = GoodsCategoryService::getModel($shopUid)->getList($shopUid, $options)['list'];
        $catIdArr = array_column($catList, 'cat_id');   //所有下级分类
//pj($catIdArr);
        $opGoods['field'] = 'id, goods_name, cost_price, purchase_price,goods_cat_id, brand_id';
        $opGoods['where'][] = ['shop_uid', '=', $shopUid];
        $opGoods['where'][] = ['goods_cat_id', 'in',  $catIdArr];
        $opGoods['where'][] = ['brand_id', '>', 0];
        $opGoods['where'][] = ['is_on_sale', '=', 1];
        $opGoods['where'][] = ['is_show', '=', 1];
        $opGoods['where'][] = ['suppliers_id', '>', 0];
        $opGoods['where'][] = ['is_buy', '=',  Goods::ON];

        $goodsList = GoodsService::getModel($shopUid)->getList($shopUid, $opGoods)['list'];
//pj($goodsList);
        $goodsListNew = array_column($goodsList, 'purchase_price', 'id');

//pj($catId, 0);
//pj($goodsList, 1);
        cache($cacheKey, json_encode($goodsListNew), $cacheTime);
        return successReturn(['data' => $goodsListNew]);
    }

    /**
     * Notes: 指定概率算法, abc之和可以是任意数 $proArr = ['a'=>50, 'b'=>40, 'c'=>10];
     * @param $proArr
     * @return int|string , 返回数组的key
     * User: SongX DateTime: 2021/9/29 16:42
     */
    private function getRand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    //根据商品ID 获取供应商信息
    private function getSupplierByGidArr($shopUid, $gidArr = []){
//pj($gidArr);
        if(empty($gidArr)){
            return successReturn(['data' => []]);
        }
        $gidArr = array_unique($gidArr);
        sort($gidArr);

        $opGoods['where'][] = ['id', 'in',  $gidArr];
        $goodsList = GoodsService::getModel($shopUid)->with(['goodsExtend'])
            ->where($opGoods['where'])->select()->toArray();
        $goodsList = array_column($goodsList, null, 'id');

        $suppliersIdArr = array_column($goodsList, 'suppliers_id');
        $suppliersIdArr = array_unique($suppliersIdArr);
        $opSupplier['field'] = 'id, supplier_name, supplier_short_name, address, contact, mobile, landline';
        $opSupplier['where'][] = ['id', 'in',  $suppliersIdArr];
        $supplierList = SupplierService::getModel()->getList($opSupplier)['list'];
        $supplierList = array_column($supplierList, null, 'id');

        $brandIdArr = array_column($goodsList, 'brand_id');
        $brandIdArr = array_unique($brandIdArr);
        $opBrand['field'] = 'id, brand_name, brand_letter';
        $opBrand['where'][] = ['id', 'in',  $brandIdArr];
        $brandList = GoodsBrandService::getModel($shopUid)->getList($shopUid, $opBrand)['list'];
        $brandList = array_column($brandList, null, 'id');
//pj($brandList);

        foreach ($goodsList as &$item) {
            $sid = $item['suppliers_id'] ?? 0;
            $bid = $item['brand_id'] ?? 0;

            $item['supplier'] = $supplierList[$sid] ?? [];
            $item['brand_name'] = $brandList[$bid]['brand_name'] ?? '';
        }

        return successReturn(['data' => $goodsList]);
    }

    /**
     * Notes: 尝试提取商品名称中的规格, 型号, 品牌
     * @param string $str
     * @return array
     * User: SongX DateTime: 2021/12/13 18:03
     */
    function getSpecsModelBrand($str){
        //$str = '九阳 （PADOOR） 电烤箱 KX32-J12 550 * 415 * 420mm';
        //$str = '派的（PADOOR）欧式简约实木复合YA-004油漆门卧室门室内门';

        $model = '';    //型号    KX32-J12
        $specs = '';    //规格    550 * 415 * 420mm
        $brand = '';

        //找规格   eg: 550 * 415 * 420mm
        $isMatched = preg_match('/(?<=[^\w])((\d+)(\*|\s|M|m)+){2,3}/', $str, $matches);
        if($isMatched){
            $specs = $matches[0];
        }
        $strNew = str_replace($specs, '', $str);    //替换掉规格     九阳  电烤箱 KX32-J12

        //找品牌   eg: （PADOOR）
        $isMatchesBrand = preg_match('/(（|\().*(）|\))/', $strNew, $matchesBrand);
        if($isMatchesBrand){
            $brand = $matchesBrand[0];
        }
        $strNew = str_replace($brand, '', $strNew);

        //找型号   eg: KX32-J12
        $isMatched2 = preg_match('/(\w+-?\w+)/', $strNew, $matches2);
        if($isMatched2){
            $model = $matches2[0];
        }
        $strNew = str_replace($model, '', $strNew);


        return [
            'model' => $model,
            'specs' => $specs,
            'guige' => $specs,
            'brand' => $brand,
            'name' => $str,
            'rubbish' => $strNew,
        ];
    }
}